<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/main}">
<head>
    <title>添加销售记录</title>
</head>
<body>
    <div layout:fragment="title">添加销售记录</div>
    
    <div layout:fragment="content">
        <div class="row">
            <div class="col-lg-8 mx-auto">
                <div class="card shadow">
                    <div class="card-header bg-warning text-dark">
                        <h5 class="mb-0">销售信息</h5>
                    </div>
                    <div class="card-body">
                        <form th:action="@{/sales/add}" th:object="${saleRecord}" method="post">
                            <!-- 商品选择 -->
                            <div class="mb-4">
                                <div class="form-group mb-3">
                                    <label for="productId" class="form-label">选择商品 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="productId" name="productId" required th:with="selectedId=${param.productId != null ? param.productId[0] : null}">
                                        <option value="">-- 请选择商品 --</option>
                                        <option th:each="product : ${products}" 
                                                th:value="${product.id}" 
                                                th:text="${product.name + ' (' + product.category + ') - 当前库存: ' + product.quantity + ' ' + product.unit}"
                                                th:selected="${selectedId != null && product.id == T(java.lang.Long).parseLong(selectedId)}"
                                                th:disabled="${product.quantity == 0}">
                                                商品名称 (分类) - 当前库存: 10 个
                                        </option>
                                    </select>
                                    <div class="form-text">库存为0的商品无法选择</div>
                                </div>
                                
                                <div class="mb-3" id="productInfo" style="display: none;">
                                    <div class="card bg-light">
                                        <div class="card-body">
                                            <h6 class="card-subtitle mb-2 text-muted">商品信息</h6>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <p><strong>商品名称:</strong> <span id="productName"></span></p>
                                                    <p><strong>分类:</strong> <span id="productCategory"></span></p>
                                                </div>
                                                <div class="col-md-6">
                                                    <p><strong>当前库存:</strong> <span id="productQuantity"></span> <span id="productUnit"></span></p>
                                                    <p><strong>销售价格:</strong> <span id="productPrice"></span> 元</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 销售数量和价格 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="quantity" class="form-label">销售数量 <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <input type="number" class="form-control" id="quantity" th:field="*{quantity}" min="1" required>
                                            <span class="input-group-text" id="quantityUnit">单位</span>
                                        </div>
                                        <div class="invalid-feedback" id="quantityFeedback">
                                            销售数量不能超过当前库存
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="price" class="form-label">单价(元) <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <input type="number" class="form-control" id="price" th:field="*{price}" step="0.01" min="0" required>
                                            <span class="input-group-text">元</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 总金额和利润计算 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="totalAmount" class="form-label">总金额(元)</label>
                                        <div class="input-group">
                                            <input type="number" class="form-control" id="totalAmount" th:field="*{totalAmount}" step="0.01" readonly>
                                            <span class="input-group-text">元</span>
                                        </div>
                                        <div class="form-text">总金额将根据数量和单价自动计算</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="profit" class="form-label">预计利润(元)</label>
                                        <div class="input-group">
                                            <input type="number" class="form-control" id="profit" th:field="*{profit}" step="0.01" readonly>
                                            <span class="input-group-text">元</span>
                                        </div>
                                        <div class="form-text">利润将根据销售价格和进货价格自动计算</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 客户信息和支付方式 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="customer" class="form-label">客户</label>
                                        <input type="text" class="form-control" id="customer" th:field="*{customer}" placeholder="输入客户姓名或公司名称">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="paymentType" class="form-label">支付方式</label>
                                        <select class="form-select" id="paymentType" th:field="*{paymentType}">
                                            <option value="现金">现金</option>
                                            <option value="微信">微信</option>
                                            <option value="支付宝">支付宝</option>
                                            <option value="银行卡">银行卡</option>
                                            <option value="赊账">赊账</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 备注信息 -->
                            <div class="form-group mb-4">
                                <label for="remark" class="form-label">备注</label>
                                <textarea class="form-control" id="remark" th:field="*{remark}" rows="2"></textarea>
                            </div>
                            
                            <!-- 按钮组 -->
                            <div class="d-flex justify-content-between">
                                <a th:href="@{/sales}" class="btn btn-secondary">取消</a>
                                <button type="submit" class="btn btn-warning" id="submitBtn">
                                    <i class="bi bi-check-circle"></i> 保存销售记录
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div layout:fragment="page_scripts">
        <script>
            // 商品信息对象
            const productData = {};
            let currentProduct = {};
            
            // 初始化页面
            document.addEventListener('DOMContentLoaded', function() {
                const productSelect = document.getElementById('productId');
                const quantityInput = document.getElementById('quantity');
                const priceInput = document.getElementById('price');
                const totalAmountInput = document.getElementById('totalAmount');
                const profitInput = document.getElementById('profit');
                const productInfo = document.getElementById('productInfo');
                const quantityUnit = document.getElementById('quantityUnit');
                const quantityFeedback = document.getElementById('quantityFeedback');
                const submitBtn = document.getElementById('submitBtn');
                
                // 获取所有商品信息
                const options = productSelect.options;
                for (let i = 1; i < options.length; i++) {
                    const option = options[i];
                    const text = option.text;
                    const matches = text.match(/(.*) \((.*)\) - 当前库存: (\d+) (.*)/);
                    
                    if (matches) {
                        productData[option.value] = {
                            name: matches[1],
                            category: matches[2],
                            quantity: parseInt(matches[3]),
                            unit: matches[4]
                        };
                    }
                }
                
                // 商品选择变更事件
                productSelect.addEventListener('change', function() {
                    const productId = this.value;
                    
                    if (productId && productData[productId]) {
                        currentProduct = productData[productId];
                        
                        // 显示商品信息
                        document.getElementById('productName').textContent = currentProduct.name;
                        document.getElementById('productCategory').textContent = currentProduct.category;
                        document.getElementById('productQuantity').textContent = currentProduct.quantity;
                        document.getElementById('productUnit').textContent = currentProduct.unit;
                        
                        // 更新单位显示
                        quantityUnit.textContent = currentProduct.unit;
                        
                        // 获取商品详细信息（包括价格）
                        fetch('/inventory/sales/product-info/' + productId)
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    currentProduct.purchasePrice = data.purchasePrice;
                                    currentProduct.sellingPrice = data.price;
                                    
                                    // 设置默认价格
                                    if (!priceInput.value) {
                                        priceInput.value = data.price || '';
                                    }
                                    
                                    document.getElementById('productPrice').textContent = data.price;
                                    
                                    // 更新计算
                                    calculateTotal();
                                }
                            })
                            .catch(error => console.error('Error:', error));
                        
                        productInfo.style.display = 'block';
                    } else {
                        productInfo.style.display = 'none';
                        currentProduct = {};
                    }
                    
                    validateQuantity();
                });
                
                // 数量输入验证
                quantityInput.addEventListener('input', function() {
                    validateQuantity();
                    calculateTotal();
                });
                
                // 价格变更时计算总金额
                priceInput.addEventListener('input', calculateTotal);
                
                // 验证库存数量
                function validateQuantity() {
                    const quantity = parseInt(quantityInput.value) || 0;
                    const productId = productSelect.value;
                    
                    if (productId && currentProduct && quantity > currentProduct.quantity) {
                        quantityInput.classList.add('is-invalid');
                        quantityFeedback.style.display = 'block';
                        submitBtn.disabled = true;
                    } else {
                        quantityInput.classList.remove('is-invalid');
                        quantityFeedback.style.display = 'none';
                        submitBtn.disabled = false;
                    }
                }
                
                // 计算总金额和利润
                function calculateTotal() {
                    const quantity = parseFloat(quantityInput.value) || 0;
                    const price = parseFloat(priceInput.value) || 0;
                    const total = quantity * price;
                    totalAmountInput.value = total.toFixed(2);
                    
                    // 计算利润
                    if (currentProduct && currentProduct.purchasePrice) {
                        const costPrice = currentProduct.purchasePrice * quantity;
                        const profit = total - costPrice;
                        profitInput.value = profit.toFixed(2);
                        
                        // 利润为负时高亮显示
                        if (profit < 0) {
                            profitInput.classList.add('text-danger');
                        } else {
                            profitInput.classList.remove('text-danger');
                        }
                    }
                }
                
                // 如果初始有选中商品，触发一次change事件
                if (productSelect.value) {
                    productSelect.dispatchEvent(new Event('change'));
                }
            });
        </script>
    </div>
</body>
</html> 